<?php

namespace app\beautiful\controller\miniapp\member;

use app\beautiful\logic\LogsLogic;

use app\beautiful\logic\PartnerLogic;
use app\beautiful\model\CouponModel;

use app\beautiful\model\GiftbagModel;
use app\beautiful\model\logs\PartnerGiftbagLogsModel;
use app\beautiful\model\member\MemberCouponModel;

use app\beautiful\model\member\MemberIntegralModel;

use app\beautiful\model\member\MemberModel;

use app\BaseController;

use app\beautiful\model\PartnerGiftbagModel;
use app\beautiful\model\PartnerModel;
use app\common\logic\DataLogic;
use think\facade\Db;
use think\Model;


class Coupon extends BaseController{

    //获取我的优惠券

    public function getMemberCoupons(){

        $type = $this->request->param('type/d',1);

        $where = [

            ['shop_id','=',$this->request->shopId],

            ['member_id','=', $this->request->memberId]

        ];

        $today = date('Y-m-d', $this->request->time());

        $member_coupon_model=new MemberCouponModel();

        if($type == 1){

            $where[] = ['status','=',0];

            $where[] = ['valid_end_time','>=',$today];

            $member_coupon_model=$member_coupon_model->where($where);

        }else{

            $map1 = $where; $map2=$where;

            $map1[]=['status','=',1];

            $map2[]=['valid_end_time','<',$today];

            $member_coupon_model=$member_coupon_model->whereOr([ $map1, $map2 ]);

        }

        $coupons = $member_coupon_model->order(['member_coupon_id' => 'desc'])

            ->page($this->request->page)->limit($this->request->limit)

            ->field('member_coupon_id,coupon_id,type_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,status')

            ->select()->toArray();

        /**
         *  "member_coupon_id": 300,
        "type_id": 1,
        "name": "礼品券00101",
        "valid_bg_time": "2022-04-23",
        "valid_end_time": "2022-05-29",
        "coupon_money": "0.00",
        "money_limit": "0.00",
        "status": 0
         */

        $data = [];

        if(! empty($coupons)){
            foreach ($coupons as $coupon){
                $coupon_info = CouponModel::find($coupon['coupon_id']);
                $coupon['coupon_type_id'] = $coupon_info->type_id;
                $data[] = $coupon;
            }
        }

        return $this->success([

            'coupons' => $data

        ]);

    }



    //获取可领取的优惠券

    public function getCouponDatas(){

        $today = date('Y-m-d', $this->request->time());

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['quota','>',0],

            ['start_time','<=',$today],

            ['end_time','>=',$today],

            ['is_integral_exchange','=',0]

        ];

        $return = [];

        $return['hasIds'] = [];

        //如果memberId 不为空的情况下

        if($this->request->memberId){

            if(null === $member = MemberModel::find($this->request->memberId)){

                return $this->error('用户登录状态不正确',100);

            }

            if($member->shop_id != $this->request->shopId){

                return $this->error('用户登录状态不正确',100);

            }

            $where[]= $member->level === null ? ['type_id','=',1] : ['type_id','IN',[1,3]];



            $hasIds = MemberCouponModel::where([

                    ['member_id','=', $this->request->memberId],

                    ['shop_id','=', $this->request->shopId],

                    ['type_id','=',1]

                ])->column('coupon_id') ?? [];

            $return['hasIds'] = $hasIds;

        }else{ //非登录情况只显示普通券

            $where[]=['type_id','=',1];

        }



        $coupons = CouponModel::where($where)

            ->order(['update_time'=>'desc','add_time'=>'desc'])

            ->limit($this->request->limit)->page($this->request->page)

            ->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit')

            ->select()->toArray();

        $return['coupons']=$coupons;

        return $this->success($return);

    }



    //获取可兑换的优惠券

    public function getExchangeCouponDatas(){

        $today = date('Y-m-d', $this->request->time());

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['quota','>',0],

            ['start_time','<=',$today],

            ['end_time','>=',$today],

            ['is_integral_exchange','=',1],

           

        ];

        if($this->request->member->level === null){ //非会员只显示1

            $where[] =  ['type_id','=',1];

        }else{

            $where[] =  ['type_id','in',[1,3]];

        }

        



        $coupons = CouponModel::where($where)

            ->order(['update_time'=>'desc','add_time'=>'desc'])

            ->limit($this->request->limit)->page($this->request->page)

            ->field('coupon_id,name,coupon_money,money_limit,exchange_integral')

            ->select()->toArray();

        $return['datas']=$coupons;

        return $this->success($return);

    }





    //领取优惠券

    public function getCoupon(){

        $coupon_id = $this->request->param('coupon_id/d');
        $partner_id = $this->request->param('partner_id/d',0);
        $giftbag_id = $this->request->param('giftbag_id/d',0);



        if(empty($coupon_id)){

            return $this->error('请选择要领取的优惠券');

        }



        $today=date('Y-m-d',$this->request->time());

        $is_exist=MemberCouponModel::where([

            ['member_id','=', $this->request->memberId],

            ['shop_id','=', $this->request->shopId],

            ['coupon_id','=',$coupon_id],

            ['type_id','=',1]

        ])->find();

        if($is_exist){

            return $this->error('此优惠券您已领过');

        }



        if(null === $coupon = CouponModel::where('coupon_id',$coupon_id)->lock(true)->find()){

            return $this->error('优惠券不存在');

        }

        if($coupon->is_delete == 1 || $coupon->shop_id != $this->request->shopId ){

            return $this->error('优惠券不存在');

        }

        if($coupon->status == -1){

            return $this->error('优惠券已经下架');

        }

        if($coupon->quota <= 0){

            return $this->error('优惠券已经领完了');

        }

        if($coupon->start_time > $today || $coupon->end_time < $today){

            return $this->error('优惠券已经过期了');

        }

        if($coupon->is_integral_exchange==1){

            return $this->error('该优惠券只能积分兑换无法领取');

        }



        $member=$this->request->member;

        $type_id = $member->level === null ? 1 : 3;


        if($coupon->type_id > $type_id  &&  $coupon->type_id != 5 ){

            return $this->error('该券为会员券，普通用户无法领取');

        }



        $coupon->quota = $coupon->quota - 1;

        $coupon->take_count = $coupon->take_count + 1;

        $mCoupon = new  MemberCouponModel();



        $mCoupon->save([

            'shop_id'       => $this->request->shopId,

            'member_id'     => $this->request->memberId,

            'type_id'       => 1,

            'coupon_id'     => $coupon->coupon_id,

            'name'          => $coupon->name,

            'coupon_money'  => $coupon->coupon_money,

            'money_limit'   => $coupon->money_limit,

            'valid_bg_time' => $coupon->valid_bg_time,

            'valid_end_time'=> $coupon->valid_end_time,

            'status'        => 0

        ]);

        $coupon->save();


        $coupon_type_id = 8;


        //合伙人绑定

        if(!empty($partner_id)){
            if(null === $partner = PartnerModel::find($partner_id)) return $this->error('合伙人不存在');

            $PartnerLogic = new PartnerLogic($this->request->shopId);
            $is_new = true;
            $pmember = MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['mobile','=',$partner->mobile]

            ])->find();

            if(null === $pmember) return $this->error('合伙人设置错误');

            $PartnerLogic->bindPartner($this->request->memberId, $pmember->member_id,$is_new);

            $coupon_type_id = 22;

            //领取礼包记录
            $this->partnerGiftbagLog($partner_id,$giftbag_id,$this->request->shopId,$this->request->memberId);

        }

        LogsLogic::coupon($this->request->shopId,$member->member_id,1,$coupon_type_id,$mCoupon->member_coupon_id,'',0);


        return $this->success([]);

    }



    //领取优惠券

    public function exchangeCoupon(){

        $coupon_id = $this->request->param('coupon_id/d');

        if(empty($coupon_id)){

            return $this->error('请选择要领取的优惠券');

        }



        $today=date('Y-m-d',$this->request->time());



        if(null === $coupon = CouponModel::where('coupon_id',$coupon_id)->lock(true)->find()){

            return $this->error('优惠券不存在');

        }

        if($coupon->is_delete == 1 || $coupon->shop_id != $this->request->shopId ){

            return $this->error('优惠券不存在');

        }

        if($coupon->status == -1){

            return $this->error('优惠券已经下架');

        }

        if($coupon->quota <= 0){

            return $this->error('优惠券已经兑换完了');

        }

        if($coupon->start_time > $today || $coupon->end_time < $today){

            return $this->error('优惠券已经过期了');

        }

        if($coupon->is_integral_exchange==0){

            return $this->error('该优惠券无法用积分兑换');

        }



        $member=$this->request->member;

        $type_id = $member->level === null ? 1 : 3;

        if($coupon->type_id > $type_id){ //会员允许兑换普通券

            return $this->error('会员券普通用户无法兑换');

        }



        $integral=$coupon->exchange_integral;



        Db::startTrans();

        try{

            //操作积分

            $myIntegral = MemberIntegralModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$this->request->memberId],

                ['expire_time','>=',$this->request->time()]

            ])->sum('remain_integral');

            if($myIntegral < $integral){

                Db::rollback();

                return $this->error('用户积分不够兑换的#1');

            }

            $needIntegral = $integral;

            while (true){

                $where = [

                    ['shop_id','=',$this->request->shopId],

                    ['member_id','=',$this->request->memberId],

                    ['expire_time','>=',$this->request->time()],

                    ['remain_integral','>',0]

                ];

                $integralModel = MemberIntegralModel::where($where)->order(['expire_time'=>'asc'])->find();

                if(null === $integralModel){

                    Db::rollback();

                    return $this->error('用户积分不够扣除的#2');

                }

                if($integralModel->remain_integral < $needIntegral){

                    $needIntegral = $needIntegral - $integralModel->remain_integral;

                    $integralModel->remain_integral = 0;

                }else{

                    $integralModel->remain_integral = $integralModel->remain_integral - $needIntegral;

                    $needIntegral = 0;

                }

                $integralModel->save();

                if($needIntegral <= 0) break;

            }



            if(!LogsLogic::integral($this->request->shopId,$this->request->memberId,-1,7,$integral,'',0)){

                Db::rollback();

                return $this->error('操作失败');

            }



            //优惠券操作

            $coupon->quota = $coupon->quota - 1;

            $coupon->take_count = $coupon->take_count + 1;

            $mCoupon = new  MemberCouponModel();



            $mCoupon->save([

                'shop_id'       => $this->request->shopId,

                'member_id'     => $this->request->memberId,

                'type_id'       => 3,

                'coupon_id'     => $coupon->coupon_id,

                'name'          => $coupon->name,

                'coupon_money'  => $coupon->coupon_money,

                'money_limit'   => $coupon->money_limit,

                'valid_bg_time' => $coupon->valid_bg_time,

                'valid_end_time'=> $coupon->valid_end_time,

                'status'        => 0

            ]);

            $coupon->save();



            LogsLogic::coupon($this->request->shopId,$this->request->memberId,1,4,$mCoupon->member_coupon_id,'',0);



            Db::commit();

            return $this->success([]);

        } catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 礼包详情
     */
    public function getGiftbagInfo()
    {
        $giftbag_id = $this->request->param('giftbag_id/d');

        if(empty($giftbag_id)){
            return $this->error('礼包参数错误');
        }

        if(null === $partner = GiftbagModel::find($giftbag_id)) return $this->error('礼包不存在');

        $order=['update_time'=>'desc','add_time'=>'desc'];

        $giftbag_coupon_ids = GiftbagModel::where('giftbag_id','=',$giftbag_id)
            ->order($order)->value('coupon_ids');

        //优惠券列表
        $today=date("Y-m-d",$this->request->time());
        $coupon_where[]=['status','=',1];
        $coupon_where[]=['end_time','>=',$today];
        $coupon_where[]=['coupon_id','in',$giftbag_coupon_ids];
        $coupon_order=['update_time'=>'desc','add_time'=>'desc'];

        $data = CouponModel::where($coupon_where)->field("coupon_id,name,type_id,valid_bg_time,valid_end_time,money_limit,coupon_money")->order($coupon_order)->select()->toArray();

        return $this->success($data);
    }


    //一键领取礼包领取优惠券

    public function getGiftbagCoupon(){

        $giftbag_id = $this->request->param('giftbag_id/d');
        $partner_id = $this->request->param('partner_id/d');

        if(empty($giftbag_id)){

            return $this->error('请选择要领取的礼包');

        }

        $today=date('Y-m-d',$this->request->time());

        if(null === $giftbag = GiftbagModel::find($giftbag_id)){

            return $this->error('礼包不存在');

        }


        //合伙人绑定
        if(null === $partner = PartnerModel::find($partner_id)) return $this->error('合伙人不存在');

        if(!empty($partner_id)){

            $PartnerLogic = new PartnerLogic($this->request->shopId);
            $is_new = true;
            $pmember = MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['mobile','=',$partner->mobile]

            ])->find();

            if(null === $pmember) return $this->error('合伙人设置错误');

            $PartnerLogic->bindPartner($this->request->memberId, $pmember->member_id,$is_new);

            //领取礼包记录
            $this->partnerGiftbagLog($partner_id,$giftbag_id,$this->request->shopId,$this->request->memberId);


        }

        $coupon_ids = explode(',',$giftbag->coupon_ids);

        foreach ($coupon_ids as $coupon_id){
            $rs =  $this->getSingleCoupon($coupon_id);
            if($rs['code'] == 400 ){
                return $this->error($rs['msg'].',请单张领取');
            }
        }


        return $this->success([]);

    }


    //一键领取礼包领取优惠券,单张领取优惠券

    public function getSingleCoupon($coupon_id){


        $today=date('Y-m-d',$this->request->time());


        if(null === $coupon = CouponModel::where('coupon_id',$coupon_id)->lock(true)->find()){

            return ['code'=>400,'msg'=>'优惠券不存在'];

        }

        $is_exist=MemberCouponModel::where([

            ['member_id','=', $this->request->memberId],

            ['shop_id','=', $this->request->shopId],

            ['coupon_id','=',$coupon_id],

            ['type_id','=',1]

        ])->find();

        if($is_exist){

            return ['code'=>400,'msg'=>'此优惠券您已领过'];


        }

        if($coupon->is_delete == 1 || $coupon->shop_id != $this->request->shopId ){

            return ['code'=>400,'msg'=>'优惠券不存在'];


        }

        if($coupon->status == -1){

            return ['code'=>400,'msg'=>'优惠券已经下架'];


        }

        if($coupon->quota <= 0){

            return ['code'=>400,'msg'=>'优惠券已经兑换完了'];


        }

        if($coupon->start_time > $today || $coupon->end_time < $today){

            return ['code'=>400,'msg'=>'优惠券已经过期了'];

        }

        if($coupon->is_integral_exchange==0){

            // return ['code'=>400,'msg'=>'该优惠券无法用积分兑换'];

        }

        $member=$this->request->member;

        $coupon->quota = $coupon->quota - 1;

        $coupon->take_count = $coupon->take_count + 1;

        $mCoupon = new  MemberCouponModel();


        $mCoupon->save([

            'shop_id'       => $this->request->shopId,

            'member_id'     => $this->request->memberId,

            'type_id'       => 1,

            'coupon_id'     => $coupon->coupon_id,

            'name'          => $coupon->name,

            'coupon_money'  => $coupon->coupon_money,

            'money_limit'   => $coupon->money_limit,

            'valid_bg_time' => $coupon->valid_bg_time,

            'valid_end_time'=> $coupon->valid_end_time,

            'status'        => 0

        ]);

        $coupon->save();


        LogsLogic::coupon($this->request->shopId,$member->member_id,1,22,$mCoupon->member_coupon_id,'',0);


        return ['code'=>200,'msg'=>'success'];

    }


    /**
     * 优惠券礼包领取记录
     * @param $partner_id
     * @param $giftbag_id
     * @param $shopId
     * @param $memberId
     */
    public function partnerGiftbagLog($partner_id,$giftbag_id,$shop_id,$member_id)
    {

        $partner_giftbag_log =PartnerGiftbagLogsModel::where([

            ['member_id','=', $member_id],

            ['shop_id','=', $shop_id],

            ['partner_id','=',$partner_id],

            ['giftbag_id','=',$giftbag_id],

        ])->find();

        if(! $partner_giftbag_log){

            $partner_giftbag_log = new PartnerGiftbagLogsModel();

            $partner_giftbag_log->shop_id=$shop_id;

            $partner_giftbag_log->member_id=$member_id;

            $partner_giftbag_log->partner_id=$partner_id;

            $partner_giftbag_log->giftbag_id=$giftbag_id;

            $partner_giftbag_log->save();

            //扣减合伙人礼包数量
            $partner_giftbag =PartnerGiftbagModel::where([

                ['shop_id','=', $shop_id],

                ['partner_id','=',$partner_id],

                ['giftbag_id','=',$giftbag_id],

            ])->find();

            if($partner_giftbag && $partner_giftbag->remand_qty > 0){
                $partner_giftbag->remand_qty = $partner_giftbag->remand_qty -1;
                $partner_giftbag->save();
            }

        }

        return true;

    }

}

